import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';

import jQuery from 'jquery';

//---------------------------------------------------------------------------------------------------------------------

//常量const（不变的）与变量let（假设）
const PI = 3.14;
let n = 123456;
console.log("1##", PI, n);


//箭头函数，可以简单理解为，是匿名函数的另外一种写法（注意：箭头函数没有自己的this值，会继承其父级作用域的this）
let plus1 = function(num1, num2) {
    return num1 + num2;
}
let plus2 = (num1, num2)=>{ //如何将普通函数改造成箭头函数？答案就是，把function去了，变成一个箭头=>
    return num1 + num2;
}
console.log(
    "2##", plus1(1, 2), plus2(1, 2)
);


//扩展运算符( spread )，可简单理解为，内含set和get两个方法，set时收集剩余参数，get时展开数组。
let demo1 = (num1, num2, ...args)=>{//收集剩余参数，args名称自定
    console.log("3##", num1, num2, args);
}
demo1(1, 2, 3, 4, 5);



let demo2 = (num1, num2, ...args)=>{//收集剩余参数，args名称自定
    console.log("4##", num1, num2, args);
}
let array = [1,2,3,4,5];
demo2(...array);//展开数组


let arr1 = [1,2,3];
let arr2 = [4,5,6];
let arr3 = [...arr1, ...arr2]//展开数组，数组展开
console.log("5##", arr3);


//默认参数值
let demo3 = (num1, num2=2, num3=3) => {
    console.log("6##", num1, num2, num3);
}
demo3(1, 3); // 1,3,3



//解构赋值，解构，就是把东西拆了，也可以简单理解为批量赋值
let [a1,b1,c1] = [1,2,3]
console.log("7##", a1, b1, c1);

let {a,b,c} = {a:1, b:2, c:3}
console.log("8##", a,b,c);



//数组
let arr4=[1,2,3];
console.log(
    "9##",
    arr4.map((item) => { //映射
        return item*2;
    })
);

let arr5=[1,2,7];
console.log(
    "10##",
    arr5.reduce((sum, item, index) => {//汇总（如求总数等）
        return sum + item;
    })//1(sum)+2(item),3(sum)+7(item) = 10
);

let arr6=[1,2,3,7,9];
console.log(
    "11##",
    arr6.filter((item) => { //过滤
        return 0==item%3;
    })
);

let arr7 = [1,2,3,7,9];
arr7.forEach((item,index) => { //迭代
    console.log("12##", index + ":" + item);
});

let str = "aowejfao";
console.log("13##", str.startsWith("a"), str.endsWith("o"));

let str1 = "World"
let str2 = `Hello ${str1}
，我爱你` //反单引号`，1 旁边那个
console.log("14##", str2);



//面向对象
class User {
    constructor(username, password) {
        this.username = username;
        this.password = password;
    }

    getUsername() { //类的内部方法，可以不加function
        return this.username;
    }

    getPassword = () => {
        return this.password;
    }
}

let user = new User("lvchanglong", "123456");

console.log(
    "15##",
    user.getUsername(),
    user.getPassword()
);

class VipUser extends User {
    constructor(username, password, realname) {
        super(username, password);

        this.realname = realname;
    }

    getRealname = () => {
        return this.realname;
    }
}

let vip = new VipUser("shensijun", "123456", "深思君");
console.log(
    "16##",
    vip.getUsername(),
    vip.getPassword(),
    vip.getRealname()
);



//JSON
let json = {a:1, b:5};
console.log("17##", JSON.stringify(json));

let str3 = '{"a":1, "b":5}';
console.log("18##", JSON.parse(str3));



//Promise，特点是“用同步的方式，写异步的代码”
let p = new Promise(function (resolve, reject) {//异步代码，resolve（解决，成功了），reject（拒绝，失败了）
    jQuery.ajax({
        url:"http://jsonplaceholder.typicode.com/users",
        dataType:"json",
        success(data){
            resolve(data);
        },
        error(err) {
            reject(err);
        }
    });
});

p.then(function(results) {
    //resolve，成功
    console.log("19##", "成功", results);
}, function(err) {
    //reject，失败
    console.log("19##", "失败", err);
});



let p1 = new Promise(function (resolve, reject) {
    jQuery.ajax({
        url:"http://jsonplaceholder.typicode.com/users",
        dataType:"json",
        success(data){
            resolve(data);
        },
        error(err) {
            reject(err);
        }
    });
});
let p2 = new Promise(function (resolve, reject) {
    jQuery.ajax({
        url:"http://jsonplaceholder.typicode.com/posts",
        dataType:"json",
        success(data){
            resolve(data);
        },
        error(err) {
            reject(err);
        }
    });
});
Promise.all([p1,p2]).then(function(results) {
    let [res1, res2] = results;
    console.log("20##", res1, res2);
}, function(err) {
    console.log("20##", err);
});



Promise.all([
    jQuery.ajax({url:"http://jsonplaceholder.typicode.com/users", dataType:"json"}),
    jQuery.ajax({url:"http://jsonplaceholder.typicode.com/posts", dataType:"json"})
]).then(function(results) {
    let [res1, res2] = results;
    console.log("21##", res1, res2);
}, function(err) {
    console.log("21##", err);
});

console.log("---------------------------------------------");

//generator，普通函数是一条路走到黑，generator执行过程中能够暂停，即开始，暂停，开始，暂停...
//主要应用于，消除异步操作，即以同步的方式写异步的代码

function* generator() { //备注：真实例子并不这么写，这里只是简单去了解
    console.log("a"); //异步ajax请求

    yield; //等待，告诉generator在哪里停，可以理解为，暂时放弃执行

    console.log("b"); //异步ajax请求
}

let gen = generator();
gen.next();//console.log("a");
gen.next();//console.log("b");


//不深入去讲了，因为generator可以理解为是一个过渡期的东西，现在常用async await来代替generator

(async () => {
    let users = await jQuery.ajax({url:"http://jsonplaceholder.typicode.com/users", dataType:"json"});
    let posts = await jQuery.ajax({url:"http://jsonplaceholder.typicode.com/posts", dataType:"json"});

    console.log("22##", users, posts);
})();

//---------------------------------------------------------------------------------------------------------------------

ReactDOM.render(<App />, document.getElementById('root'));

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: http://bit.ly/CRA-PWA
serviceWorker.unregister();
